let ws;

function initWebSocket() {
  ws = new WebSocket("ws://127.0.0.1:7979/ws");

  ws.onopen = function(event) {
    console.log("WebSocket connected:", event);
  };

  ws.onmessage = function(event) {
    const data = JSON.parse(event.data);
    const messagesDiv = document.getElementById("messages");

    const msg = document.createElement("div");
    msg.classList.add("message");

    const usernameSpan = document.createElement("span");
    usernameSpan.classList.add("username");
    usernameSpan.textContent = data.user;

    const contentSpan = document.createElement("span");
    contentSpan.textContent = ": " + data.content;

    const timeSpan = document.createElement("span");
    timeSpan.classList.add("timestamp");
    const dt = new Date(data.timestamp);
    timeSpan.textContent = ` (${dt.toLocaleTimeString()})`;

    msg.appendChild(usernameSpan);
    msg.appendChild(contentSpan);
    msg.appendChild(timeSpan);
    messagesDiv.appendChild(msg);

    messagesDiv.scrollTop = messagesDiv.scrollHeight;
  };

  ws.onclose = function(event) {
    console.log("WebSocket disconnected:", event);
    if (!event.wasClean) {
      console.warn("Connection closed unexpectedly.");
    }
  };

  ws.onerror = function(error) {
    console.error("WebSocket error:", error);
  };
}

function sendMessage() {
  const input = document.getElementById("input");
  const username = document.getElementById("username").value.trim();

  if (!username) {
    alert("Please enter your name");
    return;
  }

  const message = {
    user: username,
    content: input.value,
    timestamp: Date.now()
  };

  ws.send(JSON.stringify(message));
  input.value = '';
}

// 发送按钮绑定
document.addEventListener("DOMContentLoaded", () => {
  initWebSocket();
  document.getElementById("sendBtn").addEventListener("click", sendMessage);
  document.getElementById("input").addEventListener("keypress", e => {
    if (e.key === "Enter") {
      sendMessage();
    }
  });
});
